package com.android.infantschool.ui.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.TextView;

import com.android.infantschool.R;

/**
 * author cowards
 * created on 2019\3\26 0026
 **/
public class DialogSearchBle extends Dialog {

    private Activity activity;
    private TextView tvSearch;
    private CountDownTimer countDownTimer = null;

    public DialogSearchBle(@NonNull Activity context) {
        super(context, R.style.dialog_search);
        this.activity = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        setContentView(R.layout.dialog_search_ble);
        this.setCanceledOnTouchOutside(false);//点击dialog背景部分不消失
        this.setCancelable(true);//dialog出现时，点击back键不消失
        tvSearch = findViewById(R.id.tv_search);
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
        countDownTimer = new CountDownTimer(60 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                tvSearch.setText("正在搜索蓝牙设备...(" + millisUntilFinished / 1000L + ")");
            }

            @Override
            public void onFinish() {
                dismiss();
            }
        }.start();
    }

    @Override
    public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_HOME || keyCode == KeyEvent.KEYCODE_BACK) {
            dismiss();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void dismiss() {
        super.dismiss();
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
    }

}